import { useMemo, useState, useRef } from "react";
import styles from "./index.module.less";
import { getTableColumns, getCreateColumns, getSearchColumns } from "./constant";
import { Modal, message, Button } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import { getPostList, createPost, updatePost, deletePost } from "@/api/modules/system";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import useUrl from "@/hooks/useUrl";
import SearchBox from "@/components/SearchBox";
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import CreateForm from "@/components/CreateForm";
import { cloneDeep, omit } from "lodash";

export default () => {
	const [params, setParams] = useState({});
	const [defaultValues, setDefaultValues] = useState(null);
	const createFormRef = useRef(null);
	const dataTableRef = useRef(null);

	const handleRequest = async (params: any, sortInfo: any) => {
		const paramsCopy = cloneDeep(params);
		const newParams = omit(paramsCopy, ['pageSize', 'current'])
		const requestData: any = {
			page: {
				pageSize: params.pageSize,
				pageNum: params.current
			},
			...newParams
		};

		const res = await getPostList(requestData);
		return {
			total: res?.data?.total ?? 0,
			data: res?.data?.list ?? []
		};
	};

	const edit = {
			label: "编辑",
			value: "edit"
		},
		deleteEnum = {
			label: "删除",
			value: "delete"
		};

	const newColumns = [
		...getTableColumns({ params  }),
		{
			title: "操作",
			width: 80,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "edit":
						setDefaultValues(record);
						createFormRef?.current?.showModel();
						break;
					case "delete":
						Modal.confirm({
							icon: null,
							title: "删除提示？",
							content: `确认删除${record?.name}吗？`,
							closable: true,
							onOk: c => {
								deletePost({ id: record?.id }).then((res: any) => {
									if (res?.code === RESULT_CODES.SUCCESS) {
										message.success("删除成功");
										c?.();
										dataTableRef?.current?.reload();
									}
								});
							}
						});
						break;
				}
			},
			options: (record: any) => {
				return [edit, deleteEnum];
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchColumns();
	}, []);
	
	const CREATE_COLUMNS = useMemo(() => {
		return getCreateColumns();
	}, []);

	const handleSearch = (e: any) => {
		setParams(e);
	};

	const handleCreate = (formData: any) => {
		if(defaultValues) {
			updatePost({...formData, id: defaultValues?.id}).then((res: any) => {
				if(res.code === 200) {
					message.success("岗位更新成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，避免下次新增时回显编辑数据
					setDefaultValues(null);
				}
			})
		} else {
			createPost(formData).then((res: any) => {
				if(res.code === 200) {
					message.success("岗位创建成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 清空defaultValues，确保状态一致
					setDefaultValues(null);
				}
			})
		}
	}

	const handleAdd = () => {
		setDefaultValues(null);
		createFormRef?.current?.showModel();
	}

	return (
		<div className={styles.flexContainer}>
			<CreateForm 
				title={defaultValues ? "编辑岗位" : "创建岗位"} 
				columns={CREATE_COLUMNS} 
				onCreate={handleCreate} 
				ref={createFormRef} 
				defaultValues={defaultValues}
			>
				<></>
			</CreateForm>
			<div className={styles.rightModule}>
				<SearchBox columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} >
					<div></div>
				</SearchBox>
				<div
					className={cs({
						[styles.container]: true
					})}
				>
					<div className={styles.operation_group}>
						<Button icon={<PlusOutlined /> } type="primary" onClick={handleAdd}>新增</Button>
						{/* <Button icon={<DeleteOutlined />} type="default">删除</Button> */}
					</div>
					<SuperTable
						params={{
							...params,
						}}
						ref={dataTableRef}
						// bordered
						rowKey="id"
						columns={newColumns}
						request={handleRequest}
						scroll={{ x: "900" }}
					/>
				</div>
			</div>

		</div>
	);
};
